package com.yupi.springbootinit.manager;

import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisManager {
    @Resource
    private RedissonClient redissonClient;

    public  void  doRateLimit(String key,String BusinessName){
        String limitKeyName=BusinessName+":"+key;
        RRateLimiter rateLimiter = redissonClient.getRateLimiter(limitKeyName);
        rateLimiter.trySetRate(RateType.OVERALL,5,1, RateIntervalUnit.SECONDS);

        boolean canAcquire = rateLimiter.tryAcquire(1);
        if(!canAcquire){
            throw new BusinessException(ErrorCode.TOO_MANY_REQUEST);
        }

    }
}
